package server;

/**
 * Created with IntelliJ IDEA.
 * User: Igor Demidov
 * Date: 18.02.13
 * Time: 1:09
 */

import common.DataTransferObject;
import common.Email;
import common.LoginPassword;
import common.User;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class MyProtocol {

    public static enum Command {REGISTER, LOGIN, LOGOUT, SEND, GET_INBOX, GET_OUTBOX, OK, ERROR}
    public static enum State {LOGGED_IN, LOGGED_OUT}

    private State state = State.LOGGED_OUT;

    public DataTransferObject processInput(DataTransferObject input) throws SQLException {
        Command cmd = input.getCmd();
//        return new DataTransferObject(Command.OK);
        if (state == State.LOGGED_OUT) {
            if (cmd == Command.REGISTER) {
                User user = (User)input.getData();
                if (DataAccessObject.tryRegister(user)) {
                    return new DataTransferObject(Command.OK);
                } else {
                    return new DataTransferObject(Command.ERROR);
                }
            } else if (cmd == Command.LOGIN) {
                LoginPassword loginPassword = (LoginPassword)input.getData();
                if (DataAccessObject.tryLogin(loginPassword)) {
                    state = State.LOGGED_IN;
                    return new DataTransferObject(Command.OK);
                } else {
                    return new DataTransferObject(Command.ERROR);
                }
            } else {
                return new DataTransferObject(Command.ERROR);
            }
        } else if (state == State.LOGGED_IN) {
            if (cmd == Command.GET_INBOX) {
                String userLogin = (String)input.getData();
                List<Email> emails = DataAccessObject.getInbox(userLogin);
                return new DataTransferObject(Command.OK, emails);
            } else if (cmd == Command.GET_OUTBOX) {
                String userLogin = (String)input.getData();
                List<Email> emails = DataAccessObject.getOutbox(userLogin);
                return new DataTransferObject(Command.OK, emails);
            } else if (cmd == Command.SEND) {
                Email email = (Email)input.getData();
                if (DataAccessObject.addEmail(email)) {
                    return new DataTransferObject(Command.OK);
                } else {
                    return new DataTransferObject(Command.ERROR);
                }
            } else if (cmd == Command.LOGOUT) {
                state = State.LOGGED_OUT;
                return new DataTransferObject(Command.OK);
            } else {
                return new DataTransferObject(Command.ERROR);
            }
        }
        return null;
    }
}